﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sl.Forms
{
	public class CmdTextBox : TextBox {
		public CmdTextBox() : base() {
			Multiline = true;
			Is_Cmd_Send_clean = false;
		}
		LinkedList<string> cmd_history = new LinkedList<string>();
		LinkedListNode<string> current_node;
		string cmd_temp;
		bool is_at_end = true;
		
		///执行命令的函数，如果命令被接受则返回true，否则返回false
		public Func<string, bool> inputCmd;
		public bool Is_Cmd_Send_clean{get;set;}
		protected override void OnKeyDown(KeyEventArgs e) {
			if (e.KeyData == Keys.Enter) {
				e.Handled = true; 
				e.SuppressKeyPress = true;
				send();
			} else if (e.KeyData == Keys.Down) {
				e.Handled = true;
				e.SuppressKeyPress = true;
				if (current_node != null) {
					current_node = current_node.Next;
					if (current_node != null) {
						Text = current_node.Value;
					} else {
						is_at_end = true;
						Text = cmd_temp ?? string.Empty;
					}
				} else if (!is_at_end) {
					current_node = cmd_history.First;
					if (current_node != null) {
						Text = current_node.Value;
					}
				}
			} else if (e.KeyData == Keys.Up) {
				e.Handled = true;
				e.SuppressKeyPress = true;
				if (is_at_end) {
					cmd_temp = Text;
					current_node = cmd_history.Last;
					is_at_end = false;
					if (current_node != null) {
						Text = current_node.Value;
					}
				} else if (current_node != null && current_node.Previous != null) {
					current_node = current_node.Previous;
					Text = current_node.Value;
				}
			}
			base.OnKeyDown(e);
		}
		public void send() {
			if (inputCmd?.Invoke(Text) == true) {
				string currentCmd = Text;
				LinkedListNode<string> existingNode = cmd_history.Find(currentCmd);
				if (existingNode != null) {// 如果存在，从链表中移除
					cmd_history.Remove(existingNode);
				}
				cmd_history.AddLast(currentCmd);// 将当前命令添加到历史记录末尾
				// 重置导航状态
				is_at_end = true;
				current_node = null;
				cmd_temp = null;				
				if (Is_Cmd_Send_clean) {
					this.Clear();
				} 
			}
		}
		new public void Clear() {
			if (Text != "") {
				base.Clear();
			}
		}
	}
}
